package com.yimi.yinhepda.views.moveStock_module.load;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.MoveStockBackoutAdapter;
import com.yimi.yinhepda.db.dao.MoveStockScanMasterTableDao;
import com.yimi.yinhepda.db.dao.MoveStockScanTableDao;
import com.yimi.yinhepda.db.table.MoveStockScanMasterTable;
import com.yimi.yinhepda.db.table.MoveStockScanTable;
import com.yimi.yinhepda.entity.bean.BackoutEntity;
import com.yimi.yinhepda.entity.bean.MoveStockScanChildEntity;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: lj
 * Date: 2018/12/25
 * Description: 移库装车手动撤销界面
 */
public class MoveStockBackoutActivity extends BaseActivity {

    /**
     * 运单号
     */
    private EditText etWaybill;
    /**
     * 撤销的数据列表
     */
    private RecyclerView rvdataList;
    private TextView tvTitle;
    /**
     * 运单扫描集合
     */
    private List<MoveStockScanMasterTable> mScanEntityList;
    private String mTaskNo;
    private MoveStockScanTableDao mScanTableDao;
    private MoveStockScanMasterTableDao scanMasterTableDao;
    private MoveStockBackoutAdapter mBackoutAdapter;
    private List<BackoutEntity> mDataList;
    /**
     * 撤销计数
     */
    private TextView tvBackoutCount;
    private TextView tvNum;
    public static Handler mHandler;

    public MoveStockBackoutActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "移库装车手动撤销界面";
    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void onStart() {
        super.onStart();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MoveStockLoadScanActivity.DELETE_WAYBILL_CHILD_NO:
                        String waybill = etWaybill.getText().toString().trim();
                        deleteWaybillNo(waybill);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_move_stock_backout);

        tvNum = findViewById(R.id.num);
        tvTitle = findViewById(R.id.title);
        etWaybill = findViewById(R.id.et_waybill);
        findViewById(R.id.btn_backout).setOnClickListener(this);
        rvdataList = findViewById(R.id.rv_backout_dataList);
        tvBackoutCount = findViewById(R.id.tv_backoutCount);
        findViewById(R.id.iv_sure).setOnClickListener(this);

        tvTitle.setText("手动撤销");

        mScanTableDao = new MoveStockScanTableDao();
        scanMasterTableDao = new MoveStockScanMasterTableDao();

        mScanEntityList = MoveStockLoadScanActivity.mScanEntityList;
        mTaskNo = getIntent().getStringExtra("taksNo");

        mDataList = new ArrayList<>(0);
        mBackoutAdapter = new MoveStockBackoutAdapter(this, mDataList);
        rvdataList.setLayoutManager(new LinearLayoutManager(this));
        rvdataList.setAdapter(mBackoutAdapter);

        //注册事件
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_backout:
                //撤销按钮
                String waybill = etWaybill.getText().toString().trim();
                if ("".equals(waybill)) {
                    showToast("请先输入运单号！");
                    return;
                }
                doscan(waybill);
                break;
            case R.id.iv_sure:
                //确定按钮
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            etWaybill.setText(result);
            doscan(result);
        }
    }

    private void doscan(String result) {
        checkWaybillNo(result);
    }

    /**
     * 校验运单
     *
     * @param result 运单号
     */
    private void checkWaybillNo(String result) {
        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }

        //判断运单号是否已存在，存在则继续,不存在则查询库存件数
        MoveStockScanChildEntity tempChildEntity = null;
        if (mScanEntityList != null && !mScanEntityList.isEmpty()) {
            for (MoveStockScanMasterTable scanEntity : mScanEntityList) {
                if (result.startsWith(scanEntity.getWaybillNo())) {
                    //查询到相同主单，判断子单是否扫描
                    for (MoveStockScanChildEntity childEntity : scanEntity.getChildEntityList()) {
                        if (result.equals(childEntity.getChildWaybillNo())) {
                            tempChildEntity = childEntity;
                            break;
                        }
                    }
                    if (tempChildEntity == null) {
                        //子单未扫描
                        showToast("运单不在单据内！");
                        SoundVibratorManager.playSound(2);
                        return;
                    } else if (tempChildEntity.getFlag() != 1) {
                        //子单存在，设置为已扫描状态
                        showToast("运单未扫描上传！");
                        SoundVibratorManager.playSound(2);
                        return;
                    }

                    //发送消息请求接口撤销子单
                    Bundle data = new Bundle();
                    data.putString("childWaybillNo", result);
                    Message msg = new Message();
                    msg.setData(data);
                    msg.what = MoveStockLoadScanActivity.DELETE_WAYBILL_CHILD_NO;
                    MoveStockLoadScanActivity.mHandler.sendMessage(msg);
                    break;
                }
            }
        }
        if (tempChildEntity == null) {
            showToast("运单不在单据内！");
            SoundVibratorManager.playSound(2);
        }
    }

    /**
     * 更新本地撤销的运单状态为撤销状态（11）
     *
     * @param result
     */
    private void deleteWaybillNo(String result) {
        //判断运单号是否已存在，存在则继续,不存在则查询库存件数
        if (mScanEntityList != null && !mScanEntityList.isEmpty()) {
            for (MoveStockScanMasterTable scanEntity : mScanEntityList) {
                if (result.startsWith(scanEntity.getWaybillNo())) {
                    MoveStockScanChildEntity tempChildEntity = null;
                    //查询到相同主单，判断子单是否扫描
                    for (MoveStockScanChildEntity childEntity : scanEntity.getChildEntityList()) {
                        if (result.equals(childEntity.getChildWaybillNo())) {
                            tempChildEntity = childEntity;
                            break;
                        }
                    }
                    //修改已扫描的运单 装车为撤销（11），状态未上传
                    List<MoveStockScanTable> scanTableList = mScanTableDao.findDataByChildWaybillNo(mTaskNo, sharedPreferUtil.getValue(Common.USER_CODE), 1);
                    for (MoveStockScanTable item : scanTableList) {
                        item.setOperType(11);
                        try {
                            mScanTableDao.update(item);
                        } catch (SQLException e) {
                            SoundVibratorManager.playSound(2);
                            showToast("修改移库装车数据异常：" + e.toString());
                            return;
                        }
                    }

                    boolean isExist = false;
                    for (BackoutEntity item : mDataList) {
                        if (item.getWaybill().equals(result)) {
                            item.setCancelwaybillsNum((Integer.parseInt(item.getCancelwaybillsNum()) + 1) + "");
                            item.setScanedwaybillsNum((Integer.parseInt(item.getScanedwaybillsNum()) - 1) + "");
                            mDataList.remove(item);
                            mDataList.add(0, item);
                            isExist = true;
                            break;
                        }
                    }
                    if (!isExist) {
                        BackoutEntity backoutEntity = new BackoutEntity();
                        backoutEntity.setWaybill(result);
                        backoutEntity.setScanedwaybillsNum((scanEntity.getChildEntityList().size() - 1) + "");
                        backoutEntity.setCancelwaybillsNum("1");
                        mDataList.add(0, backoutEntity);
                    }

                    //主单界面删除已撤销的子单
                    List<MoveStockScanChildEntity> childEntityList = scanEntity.getChildEntityList();
                    childEntityList.remove(tempChildEntity);
                    if (childEntityList.isEmpty()) {
                        scanEntity.setOperType(11);
                        try {
                            scanMasterTableDao.update(scanEntity);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }

                    mBackoutAdapter.notifyDataSetChanged();
                    SoundVibratorManager.playSound(1);
                    excCount();
                    return;
                }
            }
        }
    }

    /**
     * 计算撤销的票件
     */
    private void excCount() {
        List<String> operType = new ArrayList<>(0);
        operType.add("1");
        operType.add("11");
        long unUploadCount = new MoveStockScanTableDao().getUnUploadCount(mTaskNo, operType);
        tvNum.setText(unUploadCount + "");

        Set<String> set = new HashSet<String>();
        for (BackoutEntity item : mDataList) {
            set.add(item.getWaybill().substring(0, 12));
        }

        tvBackoutCount.setText(set.size() + "/" + mDataList.size());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CountEvent countEvent) {
        tvNum.setText(countEvent.getCount() + "");
    }
}
